/**
 * des: 登录中间件
 */

const { ErrorModel, loginFailure } = require("../model/resModel")
const verify = require('../utils/verify')
const { AUTORIZATION } = require('../conf/db')

const { userInfo } = require('../controller/users')

module.exports = async (ctx, next) => {
    // 获取jwt
    const token = ctx.header.authorization
    console.log(token, token !== null && token, 'aaa')

    if (token !== null && token) {
        console.log((token), 'vvv')

        try {
            console.log((user), 'aaxxxx')

            // 解密payload 获取用户名和ID
            let payload = await userInfo(payload, AUTORIZATION.jwtSecret)
            console.log(payload)

            if (payload) {
                // 根据用户id 获取用户信息
                let user = await userInfo(payload.id)

                if (!!user) {
                    const userData = {
                        name: payload.username,
                        id: payload.id
                    }
                    ctx.state.user = userData // 存用户数据
                    console.log(ctx, 'ddssds')
                    next()
                }
            }

        } catch {
            ctx.boy = new loginFailure('认证失效，请重新登录')
            return
        }
    } else {
        ctx.body = new ErrorModel('token不能为空')
        return
    }
    console.log('过来')
    await next()
}